package com.atguigu.kafka.partitioner;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 *
 * 生产者 - 分区器
 *
 *  * Kafka配置类:
 *  *   ProducerConfig
 *  *   ConsumerConfig
 */
public class ProducerPartitionerDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1. 创建生产者对象
        Properties properties = new Properties();
        // 指定kafka集群的位置
        properties.put("bootstrap.servers", "hadoop102:9092,hadoop103:9092,hadoop104:9092");
        // 批次大小 默认16K
        properties.put("batch.size", 16384);
        // 等待时间
        properties.put("linger.ms", 1);
        // RecordAccumulator缓冲区大小 默认32M
        properties.put("buffer.memory", 33554432);

        // key,value序列化
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        // 设置分区器
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, "com.atguigu.kafka.partitioner.MyPartitioner");


        // 泛型: K ->  消息的key的类型(key可有可无) , V -> 消息的类型
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //2. 调用方法，发送消息
        for (int i = 0; i < 10; i++) {
            // 发消息
            Future<RecordMetadata> future = producer.send(
                    new ProducerRecord<String, String>("first", "shangguigu!!!>" + i),
                    new Callback() {
                        // 等结果
                        //当消息发送完成(成功或失败)后调用.
                        @Override
                        public void onCompletion(RecordMetadata metadata, Exception exception) {
                            if (exception != null) {
                                //发送失败
                                System.out.println("消息发送失败: " + exception.getMessage());
                            } else {
                                //发送成功
                                System.out.println("消息发送成功:  " + metadata.topic() + " : " + metadata.partition() + ": " + metadata.offset());
                            }
                        }
                    });
            //System.out.println("消息发送出去: "  + "atguigu!!!>" + i );
            future.get();
        }

        //3. 关闭生产者对象
        producer.close();
    }

}
